package elitech.vietnam.weatherfashion.config;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import android.media.ExifInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.view.View;
import android.webkit.URLUtil;
import android.widget.TextView;
import elitech.vietnam.weatherfashion.LoginActivity;
import elitech.vietnam.weatherfashion.MainActivity;
import elitech.vietnam.weatherfashion.R;
import elitech.vietnam.weatherfashion.WFApplication;
import elitech.vietnam.weatherfashion.dto.FriendDTO;
import elitech.vietnam.weatherfashion.dto.MemberDTO;
import elitech.vietnam.weatherfashion.dto.PostDTO;
import elitech.vietnam.weatherfashion.service.PHPSoapServiceCaller;

public class Utils {

	private Utils() {
	}

	private static final String TAG = "CONG_DEBUG";

	public static Drawable getTabDrawable(Context context, int selected, int normal) {

		StateListDrawable drawable = new StateListDrawable();

		drawable.addState(new int[] { android.R.attr.state_selected }, context.getResources().getDrawable(selected));
		drawable.addState(new int[] { android.R.attr.state_enabled }, context.getResources().getDrawable(normal));

		return drawable;
	}

	public static int getDateDrawable(String date) {
		String[] index = { "mon", "tue", "wed", "thu", "fri", "sat", "sun" };
		int[] DATE_DRAWABLE = { R.drawable.weekly_img05_a, R.drawable.weekly_img05_b, R.drawable.weekly_img05_c, R.drawable.weekly_img05_d, R.drawable.weekly_img05_e, R.drawable.weekly_img05_f,
				R.drawable.weekly_img05_g };
		for (int i = 0; i < 7; i++) {
			if (date.equalsIgnoreCase(index[i]))
				return DATE_DRAWABLE[i];
		}
		return R.drawable.ic_launcher;
	}

	public static int getDateDrawable(int index) {
		Calendar cal = Calendar.getInstance();
		int n = cal.get(Calendar.DAY_OF_WEEK);
		int[] DATE_DRAWABLE = { R.drawable.weekly_img05_g, R.drawable.weekly_img05_a, R.drawable.weekly_img05_b, R.drawable.weekly_img05_c, R.drawable.weekly_img05_d, R.drawable.weekly_img05_e,
				R.drawable.weekly_img05_f };
		int n1;
		if (n + index <= 7)
			n1 = n + index;
		else
			n1 = Math.abs(7 - (n + index));

		return DATE_DRAWABLE[n1 - 1];
	}

	public static String getDateString(Context context, String date) {
		String[] index = { "mon", "tue", "wed", "thu", "fri", "sat", "sun" };
		int[] DATE_STRING = { R.string.mon, R.string.tue, R.string.wed, R.string.thu, R.string.fri, R.string.sat, R.string.sun };
		for (int i = 0; i < 7; i++) {
			if (date.equalsIgnoreCase(index[i]))
				return context.getString(DATE_STRING[i]);
		}
		return "";
	}

	public static void LogCallService(String message) {
		android.util.Log.i("CallService", message);
	}

	public static void Log(String message) {
		android.util.Log.i(TAG, message);
	}

	public static void Log(int message) {
		android.util.Log.i(TAG, String.valueOf(message));
	}

	public static void Log(boolean message) {
		android.util.Log.i(TAG, String.valueOf(message));
	}

	//
	public static boolean isFriend(int memID) {
		if (WFApplication.getInstance().userFriends == null)
			return false;
		for (FriendDTO dto : WFApplication.getInstance().userFriends) {
			if (dto.getFriendId() == memID)
				return true;
		}
		return false;
	}

	public static String getPath(Uri uri, Activity context) {
		if (uri == null) {
			return "";
		}
		String[] projection = { MediaStore.Images.Media.DATA };
		Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);
		if (cursor != null) {
			int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
			cursor.moveToFirst();
			return cursor.getString(column_index);
		}
		return uri.getPath();
	}

	public static boolean isNetworkEnabled(Context context) {
		ConnectivityManager conMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo i = conMgr.getActiveNetworkInfo();
		if (i == null)
			return false;
		if (!i.isConnected())
			return false;
		if (!i.isAvailable())
			return false;
		return true;
	}

	public static String trimString(String string, int length) {
		String result = string.substring(0, length);
		if (string.charAt(length) != ' ' && result.lastIndexOf(" ") > 0) {
			result = result.substring(0, result.lastIndexOf(" "));
		}
		return result + "...";
	}

	public static PostDTO findPostSelf(int postID) {
		if (WFApplication.getInstance().selfData == null)
			return null;
		if (WFApplication.getInstance().selfData.isEmpty())
			return null;
		for (PostDTO dto : WFApplication.getInstance().selfData) {
			if (dto.getId() == postID)
				return dto;
		}
		return null;
	}

	// RETRIEVE APPLICATION DATA
	// TODAY DATA
	public static synchronized void getTodayData(Context context) throws IOException {
		Log("Get Today Data");
		PHPSoapServiceCaller appService = new PHPSoapServiceCaller();
		// if (AppConfig.getInstance().isGotLoc &&
		// AppConfig.getInstance().myCountryCode.equals("")) {
		// AppUtils.Log("Get country from google map by lon lat ");
		// AppConfig.getInstance().myCountryCode =
		// GoogleMapService.getCountryCode(Float.valueOf(AppConfig.getInstance().myLatitude),
		// Float.valueOf(AppConfig.getInstance().myLongtitude));
		//
		// }
		// if (AppConfig.getInstance().myCountryCode.equals("")) {
		// AppUtils.Log("Get country from other service by internet ");
		// MyLocationObject2 location2 = MyLocationService.getLocation2();
		// if (location2 != null) {
		// AppConfig.getInstance().myCountryCode = location2.getCountryCode();
		// } else {
		// MyLocationObject location = MyLocationService.getLocation();
		// if (location != null) {
		// AppConfig.getInstance().myCountryCode = location.getCountryCode();
		// }
		// }
		// }
		// if (AppConfig.getInstance().myCountryCode.equals("")) {
		// AppConfig.getInstance().myCountryCode = "KR";
		// }
		MemberDTO user = GlobalValue.getInstance(context).readUserInfo();
		int n = (user != null) ? user.getId() : -1;
		WFApplication.getInstance().todayData = appService.getFashionDayLike(0, Const.COUNTRY_CODE, n);
	}

	// WEEKLY DATA
	public static synchronized void getWeeklyData(Context context, int index) throws IOException {
		MemberDTO user = GlobalValue.getInstance(context).readUserInfo();
		if (index > 4)
			return;

		Log("Get Weekly Data " + String.valueOf(index));
		Log("Country Code: " + Const.COUNTRY_CODE);
		if (index == 0) {
			if (WFApplication.getInstance().todayData == null || WFApplication.getInstance().todayData.isEmpty())
				getTodayData(context);

			WFApplication.getInstance().weeklyData.set(index, WFApplication.getInstance().todayData);
		} else {
			PHPSoapServiceCaller appService = new PHPSoapServiceCaller();

			int n = (user != null) ? user.getId() : -1;
			WFApplication.getInstance().weeklyData.set(index, appService.getFashionDayLike(index, Const.COUNTRY_CODE, n, 0, Const.LOADMORE_PAGE_ITEMCOUNT));
		}
	}

	// STYLER ALL MEMBER DATA
	public static synchronized void getStylerAllData(Context context) throws IOException {
		Log("Get Styler All Member");
		MemberDTO user = GlobalValue.getInstance(context).readUserInfo();
		PHPSoapServiceCaller appService = new PHPSoapServiceCaller();
		int n = (user != null) ? user.getId() : -1;

		// if (AppConfig.getInstance().appUser != null)
		// try {
		// AppConfig.getInstance().stylerAllData =
		// appService.getFashionAllMemberDayLikeCountry(0, n,
		// AppConfig.getInstance().appUser.getMemberArea());
		// } catch (IOException e) {
		//
		// }
		// else

		WFApplication.getInstance().stylerAllData = appService.getFashionAllMemberDayLikeCountry(0, n, Const.COUNTRY_CODE, 0, Const.LOADMORE_PAGE_ITEMCOUNT);
	}

	// STYLER FRIEND DATA
	public static synchronized void getStylerFriendData(Context context) throws IOException {
		Log("Get Styler Friend Data");
		MemberDTO user = GlobalValue.getInstance(context).readUserInfo();
		PHPSoapServiceCaller appService = new PHPSoapServiceCaller();
		if (WFApplication.getInstance().stylerFriendData == null)
			WFApplication.getInstance().stylerFriendData = new ArrayList<PostDTO>();
		WFApplication.getInstance().stylerFriendData.clear();

		// if (AppConfig.getInstance().appUser != null)
		// try {
		// AppConfig.getInstance().stylerFriendData.addAll(appService.getFashionDayFriendLikeCountry(AppConfig.getInstance().appUser.getId(),
		// 0, AppConfig.getInstance().appUser.getMemberArea()));
		// } catch (IOException e) {
		//
		// }
		// else
		WFApplication.getInstance().stylerFriendData.addAll(appService.getFashionDayFriendLikeCountry(user.getId(), 0, Const.COUNTRY_CODE, 0, Const.LOADMORE_PAGE_ITEMCOUNT));
	}

	// SELF DATA
	public static synchronized void getSelfData(Context context) throws IOException {
		Log("Get Self Data");
		MemberDTO user = GlobalValue.getInstance(context).readUserInfo();
		PHPSoapServiceCaller appService = new PHPSoapServiceCaller();
		if (user != null)
			WFApplication.getInstance().selfData = appService.getFashionMemberLikeCountry(user.getId(), user.getId(), Const.COUNTRY_CODE, 0, Const.LOADMORE_PAGE_ITEMCOUNT);
	}
	
	// FRIENDLIST DATA
	public static synchronized void getFriendList(Context context) throws IOException {
		Log("Get Friend List");
		MemberDTO user = GlobalValue.getInstance(context).readUserInfo();
		if (user != null) {
			PHPSoapServiceCaller appService = new PHPSoapServiceCaller();
			WFApplication.getInstance().userFriends = appService.getListFriend(user.getId());
		}
	}
	
	public static synchronized void getHeartData(Context context) throws IOException {
		Log("Get Heart Data");
		MemberDTO user = GlobalValue.getInstance(context).readUserInfo();
		if (user != null) {
			PHPSoapServiceCaller appService = new PHPSoapServiceCaller();
			WFApplication.getInstance().heartData = appService.getPostLikeMember(user.getId(), Const.COUNTRY_CODE, 0, Const.LOADMORE_PAGE_ITEMCOUNT);
		}
	}

	public static synchronized void getNotificationData(Context context) throws IOException {
		Log("Get Notification Data");
		WFApplication.getInstance().mListNoti.clear();
		MemberDTO user = GlobalValue.getInstance(context).readUserInfo();
		PHPSoapServiceCaller service = new PHPSoapServiceCaller();
		if (user != null)
			WFApplication.getInstance().mListNoti = service.getNotificationUser(user.getId(), 0, Const.NOTIFICATION_PER_LOAD);
	}
	// AUTO LOGIN
	public static void LogIn() {

	}

	// =========================

	public static void openLogin(Activity context) {
		Intent intent = new Intent(context, LoginActivity.class);
		context.startActivityForResult(intent, MainActivity.REQ_CODE_LOGIN);
	}

	public static void openLink(Context context, String path) {
		Utils.Log("Open Site");
		if (URLUtil.isValidUrl(path)) {
			Uri url = Uri.parse(path);
			Intent intent = new Intent(Intent.ACTION_VIEW, url);
			context.startActivity(intent);
		} else
			openLink(context, "http://" + path);

	}

	public static String getPriceCode() {
		// if (AppConfig.getInstance().myCountryCode.equals(""))
		// return "";
		String[] pricecode = { " $", " đ", " 원", " 元" };
		String[] countrycd = { "US", "VN", "KR", "CN" };
		for (int i = 0; i < pricecode.length; i++)
			if (countrycd[i].equals(Const.COUNTRY_CODE))
				return pricecode[i];
		return "";
	}

	public static void copyFile(String src, String des) {
		try {
			InputStream in = new FileInputStream(new File(src));
			OutputStream out = new FileOutputStream(new File(des));

			// Transfer bytes from in to out
			byte[] buf = new byte[1024];
			int len;
			while ((len = in.read(buf)) > 0) {
				out.write(buf, 0, len);
			}
			in.close();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();

		}
	}

	public static void setTextUnderline(View text) {
		if (text instanceof TextView)
			((TextView) text).setPaintFlags(((TextView) text).getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
	}

	// clear data when logout
	public static void clearDataLogout(Context context) {
		Log("Clear Data logout");
		GlobalValue.getInstance(context).writeUserInfo(null);
		if (WFApplication.getInstance().userFriends != null)
			WFApplication.getInstance().userFriends.clear();
		if (WFApplication.getInstance().selfData != null)
			WFApplication.getInstance().selfData.clear();
		if (WFApplication.getInstance().heartData != null)
			WFApplication.getInstance().heartData.clear();
		if (WFApplication.getInstance().stylerFriendData != null)
			WFApplication.getInstance().stylerFriendData.clear();
		clearData();
//		WFApplication.getInstance().stopGCMNotification();
	}

	public static void clearData() {
		WFApplication.getInstance().todayData = null;
		if (WFApplication.getInstance().weeklyData != null)
			for (List<PostDTO> p : WFApplication.getInstance().weeklyData)
				if (p != null)
					p = null;
		WFApplication.getInstance().stylerAllData = null;
	}
//
//	public static BaseContainerFragment findBase(Fragment fragment) {
//		if (fragment != null) {
//			BaseContainerFragment base;
//			try {
//				base = (BaseContainerFragment) fragment;
//			} catch (ClassCastException e) {
//				base = findBase(fragment.getParentFragment());
//			}
//			if (base != null)
//				return base;
//		}
//		return null;
//	}

	public static void printDeviceScreenType(Context context) {
		switch (context.getResources().getDisplayMetrics().densityDpi) {
		case DisplayMetrics.DENSITY_LOW:
			Utils.Log("Screen Type: LDPI");
			break;
		case DisplayMetrics.DENSITY_MEDIUM:
			Utils.Log("Screen Type: MDPI");
			break;
		case DisplayMetrics.DENSITY_HIGH:
			Utils.Log("Screen Type: HDPI");
			break;
		case DisplayMetrics.DENSITY_XHIGH:
			Utils.Log("Screen Type: XHDPI");
			break;
		case DisplayMetrics.DENSITY_XXHIGH:
			Utils.Log("Screen Type: XXHDPI");
			break;

		default:
			break;
		}
	}

	// new UrlImageViewCallback() {
	// @Override
	// public void onLoaded(ImageView imageView, Bitmap loadedBitmap,
	// String url, boolean loadedFromCache) {
	// // only show the animation if it was loaded from network or disk...
	// if (!loadedFromCache) {
	// ScaleAnimation scale = new ScaleAnimation(0, 1, 0, 1,
	// ScaleAnimation.RELATIVE_TO_SELF, .5f,
	// ScaleAnimation.RELATIVE_TO_SELF, .5f);
	// scale.setDuration(140);
	// imageView.startAnimation(scale);
	// }
	// }
	// }
//	
//	public static int getDateDiff(Date start, Date end) throws ParseException {
//		final long DAY_IN_MILLIS = 1000 * 60 * 60 * 24;
//		SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
//		start = f.parse(f.format(start));
//		end = f.parse(f.format(end));
//		int result = (int) ((start.getTime() - end.getTime())/ DAY_IN_MILLIS );
//		return result;
//	}
//	
	public static String getTimeDiff(String time) {
		long secondsInMilli = 1000;
		long minutesInMilli = secondsInMilli * 60;
		long hoursInMilli = minutesInMilli * 60;
		//long daysInMilli = hoursInMilli * 24;
		
		long type1 = 5 * secondsInMilli; //5 minutes
		long type2 = 60 * secondsInMilli; //1 hour
		long type3 = 24 * 60 * secondsInMilli; //1 day

		try {
			SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault());
			Date start = f.parse(time);
			Date end = new Date();
			long different = end.getTime() - start.getTime();
			
			if (different <= type1) {
				return "Now";
			}
			if (different <= type2) {
				return different/minutesInMilli + " minutes ago";
			}
			if (different <= type3) {
				return different/hoursInMilli + " hours ago";
			}
			Calendar cal = Calendar.getInstance();
			cal.setTime(start);
			return (cal.get(Calendar.MONTH) + 1) + " month" + cal.get(Calendar.DATE) + " date";
		} catch (ParseException e) {
			e.printStackTrace();
		}
		
		return "";
	}
	

	public static int getImageRotation(String path) {
		ExifInterface ei;
		try {
			ei = new ExifInterface(path);
		} catch (IOException e) {
			e.printStackTrace();
			return 0;
		}
		int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION,
				ExifInterface.ORIENTATION_NORMAL);
		int rotate = 0;
		switch (orientation) {
		case ExifInterface.ORIENTATION_ROTATE_90:
			rotate = 90;
			break;
		case ExifInterface.ORIENTATION_ROTATE_180:
			rotate = 180;
			break;
		case ExifInterface.ORIENTATION_ROTATE_270:
			rotate = 270;
			break;
		// etc.
		default:
			break;
		}
		return rotate;
	}

}
